#include "filedata.hpp"

vector<Cwifidata> wifidata;

void fileInit()
{
    while (!SPIFFS.begin())
    {
        Serial.print("...");
    }
    Serial.println("文件系统启动");
    //初始化文件系统

    File fWifiData = SPIFFS.open("/Wifidata.txt");
    if (!fWifiData)
    {
        Serial.println("Wifi信息加载失败");
        return;
    }
    //打开Wifidata.txt文件，里面存放所有连接成功过的Wifi信息(ssid 、密码)
    //Serial.printf("File size %d\n", fWifiData.size());
    delay(100);
    while (fWifiData.available())
    {
        String line = "";
        line = fWifiData.readStringUntil('\n');
        /*
        int len = 0;
        do
        {
            line += (char)fWifiData.read();
            len++;
        } while (line[len - 1] != '\n');
        */
        //Serial.println(line);
        char ssid[32]={0}, pswd[16]={0};
        sscanf(line.c_str(), "SSID:%s PSWD:%s", ssid, pswd);
        Cwifidata temp;

        temp.ssid = ssid;
        temp.pswd = pswd;
        Serial.printf("SSID:%s PSWD:%s\r\n", temp.ssid, temp.pswd);
        delay(100);
        wifidata.push_back(temp);
    }
    fWifiData.close();
    //将Wifidata.txt中的信息加载到wifidata中维护
}

void updataWifidata(String ssid, String pswd)
{
    for (auto &line : wifidata)
    {
        if (ssid == line.ssid && pswd == line.pswd)
            return;
    }
    //判断需要导入的wifi信息是否存在

    //信息不存在
    Cwifidata temp;
    temp.ssid = ssid;
    temp.pswd = pswd;
    wifidata.push_back(temp);

    File fWifiData = SPIFFS.open("/Wifidata.txt", FILE_APPEND);
    fWifiData.printf("SSID:%s PSWD:%s\n", ssid.c_str(), pswd.c_str());
    fWifiData.close();

    Serial.println("add wifi data:");
    Serial.printf("ssid:%s,pswd:%s\r\n", ssid, pswd);
}
